package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void orderPayOverTime(){
        log.info("定时处理超时的订单:{}",new Date());
        LocalDateTime now = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,now);
        ordersList.forEach((order )-> {
            Orders orders = new Orders();
            orders.setId(order.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时，自动取消");
            orderMapper.update(orders);
        });
    }

//    /**
//     * 判断订单状态是否超时支付
//     * @param order
//     * @return
//     */
//    public Boolean orderStatus(Orders order){
//        if(order.getStatus().equals(Orders.PENDING_PAYMENT)){
//            LocalDateTime start = order.getOrderTime();
//            LocalDateTime end = LocalDateTime.now();
//            Duration duration = Duration.between(start, end);
//            //如果是同一天，判断是否超时
//            if(String.valueOf(duration.toDays()).equals("0") && duration.toMinutes() < 15){
//                return true;
//            }
//            else if(duration.toMinutes() < 15 && duration.toHours() < 1) {
//                return true;
//            }
//            else{
//                return false;
//            }
//        }
//        return true;
//    }

    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void ordersDeliveryOverTime(){
        log.info("定时处理处于派送中的订单:{}",new Date());
        LocalDateTime now = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,now);
        ordersList.forEach((order )-> {
            Orders orders = new Orders();
            orders.setId(order.getId());
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });
    }
}
